// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, must_be_immutable
import 'dart:async';
import "dart:math";

import 'package:flutter/material.dart';
import 'package:junyeyishu/ui/home/widgets/QGLimitWidget.dart';

import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';

class QGColrfulSynthesisPage extends StatefulWidget {
  String id;
  QGColrfulSynthesisPage({super.key, required this.id});
  @override
  State<QGColrfulSynthesisPage> createState() => _QGColrfulSynthesisPageState();
}

class _QGColrfulSynthesisPageState extends State<QGColrfulSynthesisPage> {
  dynamic data;

  String? countdown;
  Timer? timer;

  bool canMerge = false;

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    onRefresh();
  }

  // 时间倒计时
  setupCountdown() {
    var endTime = DateTime.parse(data?["event"]?["end_time"] ?? "")
        .millisecondsSinceEpoch;
    var now = getCurrentTime();

    countdown = getCountdown(data?["event"]?["start_time"]);
    if (countdown != null || now < endTime) {
      timer?.cancel();
      timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        var now = getCurrentTime();

        //开始时间 & 结束时间
        try {
          var startTime = DateTime.parse(data?["event"]?["start_time"] ?? "")
              .millisecondsSinceEpoch;
          var endTime = DateTime.parse(data?["event"]?["end_time"] ?? "")
              .millisecondsSinceEpoch;
          canMerge = (now >= startTime) && (now < endTime);
        } catch (e) {}

        countdown = getCountdown(data?["event"]?["start_time"]);
        if (countdown == null && now > endTime) {
          timer.cancel();
        }
        if (mounted) setState(() {});
      });
    }
  }

  onRefresh() {
    var param = {"id": widget.id};
       Map<String, dynamic> stringMap = param.cast<String, dynamic>();
    Network.post(url_synthesis_info, data: stringMap).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      updateCurrentTime(res.data["timestamp"]);

      data = res.data;

      setupCountdown();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // backgroundColor: Color(0xFFFF315F),
        body: Stack(
          children: [
            Column(),
            SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 10.rpx),
              child: Column(
                children: [
                  SizedBox(height: 50.rpx),
                  buildHeader(),
                  SizedBox(height: 20.rpx),
                  buildCondition(),
                  // buildNotice(),
                  SizedBox(height: kSafeBottom + 64.rpx),
                ],
              ),
            ),
            buildTop(),
            Positioned(bottom: 0, child: buildBottom())
          ],
        ));
  }

  buildTop() {
    return QGNavigationBar(
      title: "",
      leftItem: GestureDetector(
        onTap: () {
          Navigator.of(context).pop();
        },
        child: Container(
          padding: EdgeInsets.all(15.rpx),
          child: QGImage(asset: "nav_back_white",width: 20.rpx),
        ),
      ),
      titleStyle: TextStyle(
        color: Colors.white,
        fontSize: 16.rpx,
        fontWeight: FontWeight.bold,
      ),
      // rightItem: GestureDetector(
      //   onTap: onRecord,
      //   child: Container(
      //     padding: EdgeInsets.only(
      //       top: 7.rpx,
      //       bottom: 7.rpx,
      //       left: 14.rpx,
      //       right: 11.rpx,
      //     ),
      //     decoration: BoxDecoration(
      //       borderRadius: BorderRadius.only(
      //         topLeft: Radius.circular(20.rpx),
      //         bottomLeft: Radius.circular(20.rpx),
      //       ),
      //       color: Color(0xCCFFFFFF),
      //     ),
      //     child: Text(
      //       '合成记录3',
      //       style: TextStyle(
      //           color: Color(0xFF000000),
      //           fontSize: 11.rpx,
      //           fontWeight: FontWeight.normal),
      //     ),
      //   ),
      // ),
    );
  }

  // 图片和距离开始时间
  buildHeader() {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        // Positioned(
        //   top: -100.rpx,
        //   left: -10.rpx,
        //   child: QGImage(
        //       asset: "colorful_detail_bg", width: 375.rpx, height: 371.rpx),
        // ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            countdown != null ? Container() : SizedBox(height: 25.rpx),
            buildComposeItems(),
          ],
        ),
      ],
    );
  }

  buildComposeItems() {
    List<Widget> children = [];

    for (var item in data?["nfts"] ?? []) {
      children.add(buildComposeCell(item));
    }

    return Container(
       decoration: BoxDecoration(
        color: Color(0XFF232A32),
        borderRadius: BorderRadius.circular(10.rpx)
      ),
      padding: EdgeInsets.only(bottom: 15.rpx,top: 15.rpx),
      alignment: Alignment.center,
      child: Wrap(
        spacing: 10.rpx,
        runSpacing: 10.rpx,
        children: children,
      ),
    );
  }

  buildComposeCell(itemData) {
    return Column(
      children: [
        Container(
            decoration: BoxDecoration(
              color: Color(0XFF0C1012),
              borderRadius: BorderRadius.only(bottomLeft: Radius.circular(5.rpx),bottomRight: Radius.circular(5.rpx),),
            ),
          child: Column(
            children: [
                    QGImage(
                    url: itemData["thumb_img"],
                    width: 155.rpx,
                    height: 155.rpx),
                    SizedBox(height: 10.rpx),
                    Text(
                  itemData["name"] ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Color(0xFFffffff),
                      fontSize: 14.rpx,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 3.rpx),
                    Text(
                        '概率：${itemData?["rate_str"] ?? ""}',
                        style: TextStyle(
                            color: Color(0xFF989EA4),
                            fontSize: 12.rpx,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 10.rpx),
            ],
          ),
        ),
      ],
    );

  //   return SizedBox(
  //     width: 111.rpx,
  //     child: Stack(
  //       children: [
  //         QGImage(asset: "colorful_border_bg", width: 111.rpx),
  //         Container(
  //           padding: EdgeInsets.only(top: 11.rpx, left: 7.rpx, right: 7.rpx),
  //           child: Column(
  //             children: [
  //               ClipRRect(
  //                 borderRadius: BorderRadius.circular(10.rpx),
  //                 child: QGImage(
  //                     url: itemData?["thumb_img"] ?? "",
  //                     width: 96.rpx,
  //                     height: 96.rpx),
  //               ),
  //               SizedBox(height: 6.rpx),
  //               Container(
  //                 alignment: Alignment.center,
  //                 width: 96.rpx,
  //                 child: Text(
  //                   itemData["name"] ?? "",
  //                   maxLines: 1,
  //                   overflow: TextOverflow.ellipsis,
  //                   style: TextStyle(
  //                       color: Color(0xff111111),
  //                       fontSize: 13.rpx,
  //                       fontWeight: FontWeight.bold),
  //                 ),
  //               ),
  //               SizedBox(height: 5.rpx),
  //               Row(
  //                 mainAxisAlignment: MainAxisAlignment.center,
  //                 children: [
  //                   QGLimitWidget(
  //                     num: itemData?["max_num"] ?? "",
  //                   )
  //                 ],
  //               ),
  //               SizedBox(height: 6.rpx),
  //               RichText(
  //                   textAlign: TextAlign.center,
  //                   text: TextSpan(children: [
  //                     buildText("概率：", Color(0xFF111111)),
  //                     buildText(
  //                         '${itemData?["rate_str"] ?? ""}', Color(0xFFE32424))
  //                   ])),
  //             ],
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
   }

  buildText(text, color) {
    return TextSpan(
      text: text,
      style: TextStyle(
          color: color, fontSize: 11.rpx, fontWeight: FontWeight.normal),
    );
  }

  // 合成所需条件
  buildCondition() {
    return Column(
      children: [
        // buildConditionTitle(),
        buildConditionItems(),
      ],
    );
  }

  buildConditionTitle() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
      
        Flexible(
          child: Text(
            '合成藏品所需条件',
            style: TextStyle(
                color: Colors.white,
                fontSize: 16.rpx,
                fontWeight: FontWeight.bold),
          ),
        ),
       
      ],
    );
  }

  buildConditionItems() {
    List<Widget> children = [];

    for (var item in data?["formulas"] ?? []) {
      children.add(buildConditionCell(item));
    }

    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.all(10.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0XFF232A32)
      ),
      child: 
      Column(
        children: [
          SizedBox(height: 15.rpx,),
          Text("合成条件 ",style: TextStyle(fontSize: 18.rpx,color: Color(0XFFFFFFFF))),
          SizedBox(height: 3.rpx,),
          Text("集齐一下藏品即可兑换",style: TextStyle(fontSize: 13.rpx,color: Color(0XFF989EA4))),
          SizedBox(height: 20.rpx,),

           Wrap(
            spacing: 10.rpx,
            runSpacing: 10.rpx,
            children: children,
          ),
        ],
      )
    );
  }

  buildConditionCell(itemData) {
    return

    Column(
      children: [
        Container(
            decoration: BoxDecoration(
              color: Color(0XFF0C1012),
              borderRadius: BorderRadius.only(bottomLeft: Radius.circular(5.rpx),bottomRight: Radius.circular(5.rpx),),
            ),
          child: Column(
            children: [
                    QGImage(
                    url: itemData["thumb_img"],
                    width: 155.rpx,
                    height: 155.rpx),
                    SizedBox(height: 10.rpx),
                    Text(
                  itemData["name"] ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Color(0xFFffffff),
                      fontSize: 14.rpx,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 3.rpx),
                    Text(
                        '${itemData["goods_num_mine"]}/${itemData["goods_num"]}',
                        style: TextStyle(
                            color: Color(0xFF989EA4),
                            fontSize: 12.rpx,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 10.rpx),
            ],
          ),
        ),
      ],
    );
    
    //  Container(
    //   padding: EdgeInsets.all(15.rpx),
    //   decoration: BoxDecoration(
    //     borderRadius: BorderRadius.circular(6.rpx),
    //     color: const Color(0xFFFF315F),
    //   ),
    //   child: Column(children: [
    //     ClipRRect(
    //       borderRadius: BorderRadius.circular(4.rpx),
    //       child: QGImage(
    //           url: itemData["thumb_img"], width: 75.rpx, height: 75.rpx),
    //     ),
    //     SizedBox(height: 10.rpx),
    //     Container(
    //       alignment: Alignment.center,
    //       width: 75.rpx,
    //       child: Text(
    //         itemData["name"] ?? "",
    //         maxLines: 1,
    //         overflow: TextOverflow.ellipsis,
    //         style: TextStyle(
    //             color: Colors.white,
    //             fontSize: 14.rpx,
    //             fontWeight: FontWeight.bold),
    //       ),
    //     ),
    //     SizedBox(height: 10.rpx),
    //     Text(
    //       '拥有：${itemData["goods_num_mine"]}\n所需：${itemData["goods_num"]}',
    //       style: TextStyle(
    //           color: Colors.white,
    //           fontSize: 12.rpx,
    //           fontWeight: FontWeight.normal),
    //     ),
    //   ]),
    // );
  }

  buildNotice() {
    return Container(
      margin: EdgeInsets.only(top: 10.rpx),
      padding: EdgeInsets.all(20.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color.fromRGBO(255, 255, 255, 0.3),
      ),
      child: Column(children: [
        Text(
          '合成须知',
          style: TextStyle(
              color: Colors.white,
              fontSize: 16.rpx,
              fontWeight: FontWeight.bold),
        ),
        data?["event"]?["content"] != null
            ? SizedBox(
                height: 15.rpx,
              )
            : SizedBox(),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              child: Text(
                '${data?["event"]?["content"] ?? ""}',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 12.rpx,
                    fontWeight: FontWeight.normal),
              ),
            ),
          ],
        ),
        // QGWebViewWidget(str: data?["event"]?["content"], bgColor: "rgba(255,255,255,0.2)", textColor: "#111111")
      ]),
    );
  }

  buildBottom() {
    return Container(
      padding: EdgeInsets.only(
          left: 20.rpx,
          right: 20.rpx,
          top: 10.rpx,
          bottom: max(10, kSafeBottom)),
      width: kScreenWidth,
       decoration: BoxDecoration(color: Color(0xFF232A32)),
      child: QGButton(
        title: "立即合成",
        enable: data?["canMerge"] != 0 && canMerge,
        onTap: onCompose,
      ),
    );
  }

  onRecord() {
    Navigator.of(context)
        .pushNamed(PageColorfulSynthesisRecord, arguments: widget.id);
  }

  onCompose() {
    var param = {"id": widget.id};
    Map<String, dynamic> stringMap = param.cast<String, dynamic>();
    Network.post(url_synthesis_combineNft, data: stringMap, context: context)
        .then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      toast(res.data["message"] ?? "");
      onRefresh();
    });
  }
}
